const app = angular.module("myApp", []);

app.controller("mainController",['$scope','$compile','$sce',function($scope,$compile){
    $scope.toJSON = function (val) {
        return angular.toJson(val,true);
    };

    $scope.faults=FaultNode.faults;
    FaultNode.loadFaults.callbacks.push(()=>$scope.faults=FaultNode.faults);

    $scope.components=ComponentNode.components;
    ComponentNode.loadComponents.callbacks.push(()=>$scope.components=ComponentNode.components);

    $scope.match_functions=MatchFunctionNode.functions;
    MatchFunctionNode.loadFunctions.callbacks.push(()=>$scope.match_functions=MatchFunctionNode.functions);
}]);

app.controller("faultQueryController2",['$scope','$rootScope','$interval','$timeout','$uibModal','$http',function($scope,$rootScope,$interval,$timeout,$uibModal,$http){
    $scope.signals=[];

    $scope.attachFacts=[];

    $scope.features=FeatureNode.features;
    $scope.featureTypes = FeatureNode.featureTypes;
    // FeatureNode.loadFeatures.callbacks.push(()=>{
    //     $scope.features=FeatureNode.features;
    //     $scope.featureTypes = FeatureNode.featureTypes;
    //     $scope.$apply();
    // });

    $interval(function () {
        // $http.get('http://localhost:8080/rest/signal/list', {
        //     headers: {
        //         'Accept': 'application/json',
        //         'Content-Type': 'application/json',
        //     }}).then(function (response) {
        //     console.info(response);
        //     $scope.signals = response.data;
        //     $scope.doMatch();
        // },function (response) {
        //     console.info(response);
        // });
        $.get('http://localhost:8080/rest/signal/list2',function (data) {
            $scope.signals = data;
            $scope.doMatch();
            $scope.$apply();
        });
    },6000);

    $scope.findComponent = function(id){
        for(let cp of ComponentNode.components)
            if(cp.id==id)
                return cp;
        return {name:'未找到'};
    };

    $scope.doMatch = function () {
        FeatureNode.loadFeatures2("match (n:Feature)-[*]->(m:Component) where id(m) in $cids return n",
            {"cids":$scope.signals.map(signal=>signal.component.id)},(features,featureTypes)=>{
                $scope.features = features;
                $scope.featureTypes = featureTypes;

                for (let feature of $scope.features.filter(f=>f.isAuto())){
                    feature.isMatched = false;
                    for(let signal of $scope.signals){
                        //TODO 此处应判断元件是否匹配(元件组合AND OR)
                        let component_matched = false;
                        for (let cpIds of feature.components){
                            if(signal.component.id == cpIds){
                                component_matched = true;
                                break;
                            }
                        }
                        if(!component_matched){
                            continue;
                        }

                        //此处判断特征值是否符合
                        if(feature.name == signal.featureType){
                            feature.isMatched = matchFactory(feature.opertion)(signal.value,feature.params);
                            console.info(`${feature.opertion} ${signal.value} ${feature.params} ${feature.isMatched}`);
                        }
                    }
                }

                $scope.faults = [];
                $scope.features//.filter(feature=>feature.isMatched)
                    .forEach((feature,index)=>{
                        if(!feature.isMatched)
                            return;
                        let session2 = neo4jService.getSession();
                        let resultPromise2 = session2.run(`start f=node(${feature.id}) MATCH (a:Fault)-[*]->(f) RETURN a`);
                        resultPromise2.then(result => {
                            session2.close();
                            // console.info(result);
                            result.records
                                .map((record)=>record.get(0))
                                .map(node=>MyNode.fromNeo4jNode(node))
                                .forEach(fault=>{
                                    fault.$state='partial';

                                    $scope.features[index].$formFaults=fault.id;

                                    let f_contains = false;
                                    for (let ff of $scope.faults){
                                        if(ff.id==fault.id){
                                            f_contains = true;
                                            break;
                                        }
                                    }
                                    if(!f_contains){
                                        $scope.faults.push(fault);

                                        let session4 = neo4jService.getSession();
                                        let resultPromise4 = session4.run(`start f=node(${fault.id}) MATCH (f)-[:hasFeatures]->(a) RETURN a`);
                                        resultPromise4.then(result=>{
                                            session4.close();

                                            let nd = result.records[0].get(0);
                                            $scope.matchFeature(nd,function () {
                                                fault.state='all';
                                                $scope.$apply();
                                            });
                                        });
                                    }
                                });
                        });
                    });
            });
    };

    $scope.matchFeature = function(f,func){
        if(f["labels"][0]=='Feature'){
            //TODO 在此处补充对元件组的判断
            for (let ff of $scope.features){
                if(ff.id==f["identity"].toString()){
                    if(ff.isMatched){
                        func();
                    }
                }
            }
        }
        else {
            let type = f.properties['type'];
            let session = neo4jService.getSession();
            let resultPromise = session.run(`start f=node(${f["identity"].toString()}) MATCH (f)-[:contains]->(a) RETURN a`);
            resultPromise.then(result => {
                session.close();

                let nds = result.records.map((record) => record.get(0));

                if (type == 'or') {
                    for (let nd of nds) {
                        $scope.matchFeature(nd, func);
                    }
                } else {
                    let ct = 0;
                    for (let nd of nds) {
                        $scope.matchFeature(nd, function () {
                            ct++;
                            if (ct == nds.length) {
                                func();
                            }
                        });
                    }
                }
            });
        }
    };

    $scope.showFaultTree = function (faultId) {
        // let query = `start n=node(${faultId}) match (n)-[*]->(p) return n,p`;
        // window.open(`http://127.0.0.1:8080/browser/NeoEmbed.html?query=${encodeURIComponent(query).replace(/=/g,'%3d')}`);
        // $rootScope.$broadcast('graph_fault_show', { message: faultId });
        // $('#myTabs li:eq(1) a').tab('show');

    };

    $scope.showFaultReport = function (faultId) {
        let fault = null;
        for(let f of $scope.faults){
            if(f.id==faultId){
                fault = f;
                break;
            }
        }
        let features = [];
        $scope.features.forEach(f=>{
            if(f.$formFaults==faultId){
                features.push(f);
            }
        });
        $scope.modelData = {
            fault:fault,
            features:features
        };//用于传递数据

        let modalInstance = $uibModal.open({
            templateUrl : 'template/report.html',//script标签中定义的id
            controller : 'ReportController',//modal对应的Controller
            scope:$scope
        });
    };

    $scope.showNowReport=function () {
        $scope.modelData = {
            fault:null,
            features:[]
        };//用于传递数据

        let modalInstance = $uibModal.open({
            templateUrl : 'template/report.html',//script标签中定义的id
            controller : 'ReportController',//modal对应的Controller
            scope:$scope
        });
    };

    $scope.matchFaultTree = function (faultId) {
        $scope.matchingFaultId = faultId;
    };

    $scope.matchingFaultId = 0;
}]);

app.controller('ReportController',['$scope', '$uibModalInstance','$window', function($scope, $uibModalInstance,$window) {
    $scope.fault= $scope.modelData.fault;
    $scope.features = $scope.modelData.features;

    console.info($scope.modelData);

    $scope.sequence = '001232016072010010121001';

    $scope.reasons = [];

    if($scope.fault != null){
        Graph.loadGraph($scope.fault.id,g=>{
            $scope.graph = g;
            let nodesList = [... g.nodes.values()];
            $scope.reasons = nodesList.filter(node=>node.$type=='Reason').sort((a,b)=>a>b);
            $scope.$apply();
        });
    }

    $scope.getNow=function () {
        return new Date();
    };

    //在这里处理要进行的操作
    $scope.ok = function() {
        $window.print();
        $uibModalInstance.close();
    };
    $scope.cancel = function() {
        $uibModalInstance.dismiss('cancel');
    }
}]);
